package org.chris.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.chris.model.SupplierModel;
import org.chris.service.SupplierService;
import org.nutz.dao.Cnd;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.service.IdEntityService;
@IocBean(name="supplierService", fields={"dao"})
public class SupplierServiceImpl extends IdEntityService<SupplierModel> implements SupplierService {
	public Map<String, Object> delete(String... ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			this.dao().clear(SupplierModel.class, Cnd.where("id", "in", ids));
			result.put("type", "0");
			result.put("message", "删除成功");
		} catch (RuntimeException e) {
			result.put("type", "1");
			result.put("message", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	public SupplierModel find(int id){
		SupplierModel model = this.dao().fetch(SupplierModel.class, id);
		this.dao().fetchLinks(model, "employee");
		return model;
	}
	
	public List<SupplierModel> init(){
		return this.dao().query(SupplierModel.class,null);
	}

	public Map<String, Object> query(HttpServletRequest request, int rows,int page) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String username = request.getParameter("username");
			Criteria cn = Cnd.cri();
			if(!Strings.isEmpty(username)){
				cn.where().andEquals("username", username);
			}
			Pager pager = new Pager();
			pager.setPageNumber(page);
			pager.setPageSize(rows);
			List<SupplierModel> list = this.dao().query(SupplierModel.class, cn,pager);
			for(SupplierModel model : list){
				this.dao().fetchLinks(model, "employee");
			}
			result.put("total", list.size());
			result.put("rows", list);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return result;
	}

	public Map<String, Object> save(SupplierModel model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			SupplierModel query = this.dao().fetch(SupplierModel.class, model.getId());
			if(null!=query){
				this.dao().update(model);
			}else{
				this.dao().insert(model);
			}
			result.put("type", "0");
			result.put("message", "保存成功");
		} catch (RuntimeException e) {
			result.put("type", "1");
			result.put("message", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
}
